package com.phiture.erp.finance.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import com.phiture.erp.basic.api.pojo.resp.ErpAccountResp;
import com.phiture.erp.basic.api.service.ErpAccountApi;
import com.phiture.erp.basic.api.service.ErpCustomerApi;
import com.phiture.erp.common.constants.ErpNoPrefixConstants;
import com.phiture.erp.common.enums.ErpAuditStatus;
import com.phiture.erp.common.utils.ErpNoGenerator;
import com.phiture.erp.finance.core.event.ErpFinanceReceiptEvent;
import com.phiture.erp.finance.core.pojo.dto.ErpFinanceReceiptEventDTO;
import com.phiture.erp.finance.core.pojo.dto.GenerateErpFinanceReceiptDTO;
import com.phiture.erp.finance.core.pojo.vo.receipt.ErpFinanceReceiptPageReqVO;
import com.phiture.erp.finance.core.pojo.vo.receipt.ErpFinanceReceiptSaveReqVO;
import com.phiture.erp.finance.core.service.ErpFinanceReceiptService;
import com.phiture.erp.finance.core.service.ErpFinanceStatementService;
import com.phiture.erp.finance.dal.entity.ErpFinanceReceiptDO;
import com.phiture.erp.finance.dal.entity.ErpFinanceReceiptItemDO;
import com.phiture.erp.finance.dal.entity.ErpFinanceStatementDO;
import com.phiture.erp.finance.dal.mapper.ErpFinanceReceiptItemMapper;
import com.phiture.erp.finance.dal.mapper.ErpFinanceReceiptMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static com.phiture.erp.common.constants.ErrorCodeConstants.*;

// TODO 芋艿：记录操作日志

/**
 * ERP 收款单 Service 实现类
 *
 * @author 芋道源码
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class ErpFinanceReceiptServiceImpl implements ErpFinanceReceiptService {
    private final ErpFinanceReceiptMapper financeReceiptMapper;
    private final ErpFinanceReceiptItemMapper financeReceiptItemMapper;
    private final ErpNoGenerator erpNoGenerator;
    private final ErpCustomerApi customerService;
    private final ErpAccountApi accountService;
    private final ErpFinanceStatementService financeStatementService;
    private final AdminUserApi adminUserApi;
    private final ErpAccountApi accountApi;
    private final TransactionTemplate transactionTemplate;
    private final ApplicationEventPublisher eventPublisher;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createFinanceReceipt(ErpFinanceReceiptSaveReqVO createReqVO) {
        // 1.1 校验订单项的有效性
        List<ErpFinanceReceiptItemDO> receiptItems = validateFinanceReceiptItems(
                createReqVO.getCustomerId(), createReqVO.getItems());
        // 1.2 校验客户
        customerService.validateCustomer(createReqVO.getCustomerId());
        // 1.3 校验结算账户
        if (createReqVO.getAccountId() != null) {
            accountService.validateAccount(createReqVO.getAccountId());
        }
        // 1.4 校验财务人员
        if (createReqVO.getFinanceUserId() != null) {
            adminUserApi.validateUser(createReqVO.getFinanceUserId());
        }
        // 1.5 生成收款单号，并校验唯一性
        String no = getFinanceReceiptNo();
        if (financeReceiptMapper.selectByNo(no) != null) {
            throw exception(FINANCE_RECEIPT_NO_EXISTS);
        }

        // 2.1 插入收款单
        ErpFinanceReceiptDO receipt = BeanUtils.toBean(createReqVO, ErpFinanceReceiptDO.class, in -> in
                .setNo(no).setStatus(ErpAuditStatus.PROCESS.getStatus()));
        calculateTotalPrice(receipt, receiptItems);
        financeReceiptMapper.insert(receipt);
        // 2.2 插入收款单项
        receiptItems.forEach(o -> o.setReceiptId(receipt.getId()));
        financeReceiptItemMapper.insertBatch(receiptItems);

        // 3. 更新销售出库、退货的收款金额情况
        updateSalePrice(receiptItems);
        return receipt.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFinanceReceipt(ErpFinanceReceiptSaveReqVO updateReqVO) {
        // 1.1 校验存在
        ErpFinanceReceiptDO receipt = validateFinanceReceiptExists(updateReqVO.getId());
        if (ErpAuditStatus.APPROVE.getStatus().equals(receipt.getStatus())) {
            throw exception(FINANCE_RECEIPT_UPDATE_FAIL_APPROVE, receipt.getNo());
        }
        // 1.2 校验客户
        customerService.validateCustomer(updateReqVO.getCustomerId());
        // 1.3 校验结算账户
        if (updateReqVO.getAccountId() != null) {
            accountService.validateAccount(updateReqVO.getAccountId());
        }
        // 1.4 校验财务人员
        if (updateReqVO.getFinanceUserId() != null) {
            adminUserApi.validateUser(updateReqVO.getFinanceUserId());
        }
        // 1.5 校验收款单项的有效性
        List<ErpFinanceReceiptItemDO> receiptItems = validateFinanceReceiptItems(
                updateReqVO.getCustomerId(), updateReqVO.getItems());

        // 2.1 更新收款单
        ErpFinanceReceiptDO updateObj = BeanUtils.toBean(updateReqVO, ErpFinanceReceiptDO.class);
        calculateTotalPrice(updateObj, receiptItems);
        financeReceiptMapper.updateById(updateObj);
        // 2.2 更新收款单项
        updateFinanceReceiptItemList(updateReqVO.getId(), receiptItems);
    }

    private void calculateTotalPrice(ErpFinanceReceiptDO receipt, List<ErpFinanceReceiptItemDO> receiptItems) {
        receipt.setTotalPrice(getSumValue(receiptItems, ErpFinanceReceiptItemDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO));
//        receipt.setReceiptPrice(receipt.getTotalPrice().subtract(receipt.getDiscountPrice()));
        receipt.setReceiptPrice(getSumValue(receiptItems, ErpFinanceReceiptItemDO::getReceiptPrice, BigDecimal::add, BigDecimal.ZERO));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFinanceReceiptStatus(Long id, Integer status) {
        boolean approve = ErpAuditStatus.APPROVE.getStatus().equals(status);
        // 1.1 校验存在
        ErpFinanceReceiptDO receipt = validateFinanceReceiptExists(id);
        // 1.2 校验状态
        if (receipt.getStatus().equals(status)) {
            throw exception(approve ? FINANCE_RECEIPT_APPROVE_FAIL : FINANCE_RECEIPT_PROCESS_FAIL);
        }

        // 2. 更新状态
        int updateCount = financeReceiptMapper.updateByIdAndStatus(id, receipt.getStatus(),
                new ErpFinanceReceiptDO().setStatus(status));
        if (updateCount == 0) {
            throw exception(approve ? FINANCE_RECEIPT_APPROVE_FAIL : FINANCE_RECEIPT_PROCESS_FAIL);
        }
        eventPublisher.publishEvent(new ErpFinanceReceiptEvent(this, ErpFinanceReceiptEventDTO.of(id, status)));

    }

    private List<ErpFinanceReceiptItemDO> validateFinanceReceiptItems(
            Long customerId,
            List<ErpFinanceReceiptSaveReqVO.Item> list) {
        return convertList(list, o -> BeanUtils.toBean(o, ErpFinanceReceiptItemDO.class));
    }

    private void updateFinanceReceiptItemList(Long id, List<ErpFinanceReceiptItemDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<ErpFinanceReceiptItemDO> oldList = financeReceiptItemMapper.selectListByReceiptId(id);
        List<List<ErpFinanceReceiptItemDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setReceiptId(id));
            financeReceiptItemMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            financeReceiptItemMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            financeReceiptItemMapper.deleteBatchIds(convertList(diffList.get(2), ErpFinanceReceiptItemDO::getId));
        }

        // 第三步，更新销售出库、退货的收款金额情况
        updateSalePrice(CollectionUtils.newArrayList(diffList));
    }

    private void updateSalePrice(List<ErpFinanceReceiptItemDO> receiptItems) {
//        receiptItems.forEach(receiptItem -> {
//            BigDecimal totalReceiptPrice = financeReceiptItemMapper.selectReceiptPriceSumByBizIdAndBizType(
//                    receiptItem.getBizId(), receiptItem.getBizType());
//            if (ErpBizTypeEnum.SALE_OUT.getType().equals(receiptItem.getBizType())) {
//                saleOutService.updateSaleInReceiptPrice(receiptItem.getBizId(), totalReceiptPrice);
//            } else if (ErpBizTypeEnum.SALE_RETURN.getType().equals(receiptItem.getBizType())) {
//                saleReturnService.updateSaleReturnRefundPrice(receiptItem.getBizId(), totalReceiptPrice.negate());
//            } else {
//                throw new IllegalArgumentException("业务类型不正确：" + receiptItem.getBizType());
//            }
//        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFinanceReceipt(List<Long> ids) {
        // 1. 校验不处于已审批
        List<ErpFinanceReceiptDO> receipts = financeReceiptMapper.selectBatchIds(ids);
        if (CollUtil.isEmpty(receipts)) {
            return;
        }
        receipts.forEach(receipt -> {
            if (ErpAuditStatus.APPROVE.getStatus().equals(receipt.getStatus())) {
                throw exception(FINANCE_RECEIPT_DELETE_FAIL_APPROVE, receipt.getNo());
            }
        });

        // 2. 遍历删除，并记录操作日志
        receipts.forEach(receipt -> {
            // 2.1 删除收款单
            financeReceiptMapper.deleteById(receipt.getId());
            // 2.2 删除收款单项
            List<ErpFinanceReceiptItemDO> receiptItems = financeReceiptItemMapper.selectListByReceiptId(receipt.getId());
            financeReceiptItemMapper.deleteBatchIds(convertSet(receiptItems, ErpFinanceReceiptItemDO::getId));

            // 2.3 更新销售出库、退货的收款金额情况
            updateSalePrice(receiptItems);
        });
    }

    private ErpFinanceReceiptDO validateFinanceReceiptExists(Long id) {
        ErpFinanceReceiptDO receipt = financeReceiptMapper.selectById(id);
        if (receipt == null) {
            throw exception(FINANCE_RECEIPT_NOT_EXISTS);
        }
        return receipt;
    }

    @Override
    public ErpFinanceReceiptDO getFinanceReceipt(Long id) {
        return financeReceiptMapper.selectById(id);
    }

    @Override
    public PageResult<ErpFinanceReceiptDO> getFinanceReceiptPage(ErpFinanceReceiptPageReqVO reqVO) {
            MPJLambdaWrapperX<ErpFinanceReceiptDO> query = new MPJLambdaWrapperX<ErpFinanceReceiptDO>()
                    .likeIfPresent(ErpFinanceReceiptDO::getNo, reqVO.getNo())
                    .betweenIfPresent(ErpFinanceReceiptDO::getReceiptTime, reqVO.getReceiptTime())
                    .eqIfPresent(ErpFinanceReceiptDO::getCustomerId, reqVO.getCustomerId())
                    .eqIfPresent(ErpFinanceReceiptDO::getCreator, reqVO.getCreator())
                    .eqIfPresent(ErpFinanceReceiptDO::getFinanceUserId, reqVO.getFinanceUserId())
                    .eqIfPresent(ErpFinanceReceiptDO::getAccountId, reqVO.getAccountId())
                    .eqIfPresent(ErpFinanceReceiptDO::getStatus, reqVO.getStatus())
                    .likeIfPresent(ErpFinanceReceiptDO::getRemark, reqVO.getRemark())
                    .orderByDesc(ErpFinanceReceiptDO::getId);
            if (reqVO.getBizNo() != null) {
                query.leftJoin(ErpFinanceReceiptItemDO.class, ErpFinanceReceiptItemDO::getReceiptId, ErpFinanceReceiptDO::getId)
                        .eq(reqVO.getBizNo() != null, ErpFinanceReceiptItemDO::getBizNo, reqVO.getBizNo())
                        .groupBy(ErpFinanceReceiptDO::getId); // 避免 1 对多查询，产生相同的 1
            }
            return financeReceiptMapper.selectJoinPage(reqVO, ErpFinanceReceiptDO.class, query);
    }

    // ==================== 收款单项 ====================

    @Override
    public List<ErpFinanceReceiptItemDO> getFinanceReceiptItemListByReceiptId(Long receiptId) {
        return financeReceiptItemMapper.selectListByReceiptId(receiptId);
    }

    @Override
    public List<ErpFinanceReceiptItemDO> getFinanceReceiptItemListByReceiptIds(Collection<Long> receiptIds) {
        if (CollUtil.isEmpty(receiptIds)) {
            return Collections.emptyList();
        }
        return financeReceiptItemMapper.selectListByReceiptIds(receiptIds);
    }

    @Override
    public void generateReceipt(GenerateErpFinanceReceiptDTO dto) {
        if(CollUtil.isEmpty(dto.getStatementNos())){
            log.error("[ErpFinanceReceiptService.generateReceipt] 收款单生成失败，对账单号为空");
            throw exception(FINANCE_RECEIPT_GENERATE_ERROR);
        }

        List<ErpFinanceStatementDO> financeStatementList = financeStatementService.getListByFinanceStatementNos(new HashSet<>(dto.getStatementNos()));
        if(CollUtil.isEmpty(financeStatementList)){
            log.error("[ErpFinanceReceiptService.generateReceipt] 收款单生成失败，对账单不存在，financeStatementNos:{}", JsonUtils.toJsonString(dto.getStatementNos()));
            throw exception(FINANCE_STATEMENT_NOT_EXISTS);
        }

        ErpAccountResp defaultAccount = accountApi.getDefaultAccount();
        Assert.notNull(defaultAccount, "该用户没有默认账户");
        boolean settleTheBill = Boolean.TRUE.equals(dto.getSettleTheBill());

        Map<Long, ErpFinanceReceiptDO> financeReceiptMap = new HashMap<>(financeStatementList.size());
        financeStatementList.forEach(item ->{
            financeReceiptMap.merge(
                    item.getTransactionUserId(),
                    toErpFinanceReceiptDO(item.getTransactionUserId(), defaultAccount.getId(), item.getTotalAmount(), item.getBillingPeriod(), settleTheBill),
                    (originalVal, newVal) -> {
                        originalVal.setTotalPrice(originalVal.getTotalPrice().add(newVal.getTotalPrice()));
                        originalVal.setReceiptPrice(originalVal.getReceiptPrice().add(newVal.getReceiptPrice()));
                        return originalVal;
                    }
            );
        });

        List<ErpFinanceReceiptDO> saveList = new ArrayList<>(financeReceiptMap.values());
        transactionTemplate.execute(action ->{
            Boolean batch = financeReceiptMapper.insertBatch(saveList);
            if(batch){
                Map<Long, Long> financeReceiptIdMap = saveList.stream().collect(Collectors.toMap(ErpFinanceReceiptDO::getCustomerId, ErpFinanceReceiptDO::getId));
                List<ErpFinanceReceiptItemDO> items = financeStatementList.stream().map(item ->
                        toErpFinanceReceiptItemDO(
                                financeReceiptIdMap.get(item.getTransactionUserId()),
                                item.getId(),
                                item.getNo(),
                                item.getTotalAmount(),
                                item.getTransactionAmount(),
                                settleTheBill
                        )
                ).collect(Collectors.toList());
                financeReceiptItemMapper.insertBatch(items);
            }
            return true;
        });
    }

    private String getFinanceReceiptNo(){
        return erpNoGenerator.generate(ErpNoPrefixConstants.FINANCE_RECEIPT_NO_PREFIX);
    }

    private ErpFinanceReceiptDO toErpFinanceReceiptDO(Long customerId, Long defaultAccountId, BigDecimal totalPrice, String billingPeriod, boolean settleTheBill){
        ErpFinanceReceiptDO receiptDO = new ErpFinanceReceiptDO();
        receiptDO.setReceiptTime(LocalDateTime.now());
        receiptDO.setNo(getFinanceReceiptNo());
        receiptDO.setStatus(ErpAuditStatus.PROCESS.getStatus());
        receiptDO.setFinanceUserId(SecurityFrameworkUtils.getLoginUserId());
        receiptDO.setAccountId(defaultAccountId);
        receiptDO.setCustomerId(customerId);
        receiptDO.setTotalPrice(totalPrice);
        receiptDO.setDiscountPrice(BigDecimal.ZERO);
        if(settleTheBill){
            receiptDO.setReceiptPrice(receiptDO.getTotalPrice().subtract(receiptDO.getDiscountPrice()));
        } else {
            receiptDO.setReceiptPrice(BigDecimal.ZERO);
        }
        receiptDO.setBillingPeriod(billingPeriod);
        return receiptDO;
    }

    private ErpFinanceReceiptItemDO toErpFinanceReceiptItemDO(Long receiptId, Long bizId, String bizNo, BigDecimal totalPrice, BigDecimal receiptedPrice, boolean settleTheBill){
        ErpFinanceReceiptItemDO itemDO = new ErpFinanceReceiptItemDO();
        itemDO.setReceiptId(receiptId);
        itemDO.setBizId(bizId);
        itemDO.setBizNo(bizNo);
        itemDO.setTotalPrice(totalPrice);
        itemDO.setReceiptedPrice(receiptedPrice);
        if(settleTheBill){
            itemDO.setReceiptPrice(totalPrice.subtract(receiptedPrice));
        }else {
            itemDO.setReceiptPrice(BigDecimal.ZERO);
        }
        return itemDO;
    }

}